require 'librmpd'

class Jukebox
  cattr_accessor :radio
  
  #If the daemon is not running, start it!
  def self.start_callbacks_daemon
      status = MiddleMan.ask_status(:worker => :mpd_callbacks_worker)
      MiddleMan.ask_work(:worker => :mpd_callbacks_worker, :worker_method => :catch_callbacks) if status != 'running'
  end
  
  #Start te backgroundrb daemon
  def self.start_backgroundrb
    `"#{RAILS_ROOT}/script/backgroundrb" start`
  end
  
  def self.playlist
    Playlist.find :first
  end
  
  def self.mpd_config
      config = YAML.load_file("#{RAILS_ROOT}/config/mpd.yml")[RAILS_ENV]
      { :host => config['host'] || 'localhost',
        :port => config['port'] || 6600,
        :password => config['password']
      }
  end
  
  def self.radio
    if @@radio.nil?
      self.radio = MPD.new(mpd_config[:host], mpd_config[:port])
      @@radio.connect #True because of the callbacks
    elsif @@radio.connected? == false
      @@radio.connect
    end
    
    @@radio
  end
  
  def self.if_not_playing_make_it_so
    Jukebox.radio.play if not Jukebox.radio.playing? && Jukebox.playlist.number_of_items > 0
  end
end
